package com.edoomath.api.web.controller.user;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.demo2do.core.entity.result.HttpResult;
import com.edoomath.api.servcice.UserService;
import com.edoomath.entity.user.ConsumeTag;
import com.edoomath.entity.user.User;
import com.edoomath.entity.user.UserConsumeRecorder;
import com.edoomath.entity.user.UserWallet;

/**
 * 
 * @author mohanlan
 *
 */
@Controller
@RequestMapping("/users")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    /**
     * 
     * @param unionid
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult create(@RequestParam(value = "unionid", required = true) String unionid) {
        
        HttpResult httpResult = new HttpResult();
        
        User user = userService.create(unionid);
        
        return httpResult.success()
                         .data("user", user)
                         .message("创建基于微信的用户成功");
    }
    
    /**
     * 
     * @param unionid
     * @param email
     * @return
     */
    @RequestMapping(value = "/{unionid}/email", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult bindEmail(@PathVariable("unionid") String unionid,
                                @RequestParam(value = "email") String email) {
        
        HttpResult httpResult = new HttpResult();
        
        // bind email here
        userService.editEmail(unionid, email);
        
        return httpResult.success()
                         .message("修改用户邮箱成功");
    }
    
    /**
     * 
     * @param unionid
     * @return
     */
    @RequestMapping(value = "/{unionid}/bonus-records", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult bonusRecord(@PathVariable("unionid") String unionid) {
    	
    	HttpResult httpResult = new HttpResult();
    	
    	User user = userService.load(unionid);
    	UserWallet wallet = userService.saveOrGetUserWallet(user);
    	
    	List<ConsumeTag> tags = new ArrayList<ConsumeTag>();
    	tags.add(ConsumeTag.BONUS_CONSUME);
    	tags.add(ConsumeTag.BONUS_WITHDRAWAL);
    	tags.add(ConsumeTag.SIGNIN_BONUS_IN);
    	
    	List<UserConsumeRecorder> recorders = userService.listRecords(user, tags);
    	
    	return httpResult.success()
    				     .data("wallet", wallet)
    				     .data("walletRecords", recorders)
    					 .message("获取奖励金成功");
    }
}
